package com.gexiaobao.pigeon.ui.fragment.mall

import android.graphics.Color
import android.graphics.Rect
import android.os.Bundle
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import androidx.activity.OnBackPressedCallback
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.hideSoftKeyboard
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.loadListData
import com.gexiaobao.pigeon.app.ext.loadServiceInit
import com.gexiaobao.pigeon.app.ext.showLoading
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.databinding.FragmentSearchResultBinding
import com.gexiaobao.pigeon.ui.adapter.MallProductAdapter
import com.gexiaobao.pigeon.ui.mall.MallViewModel
import com.kingja.loadsir.core.LoadService
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat

/**
 * @Author      : hxw
 * @Date        : 2023/6/15 14:52
 * @Describe    : 搜索结果
 */
class FragmentSearchResult : BaseFragment<MallViewModel, FragmentSearchResultBinding>() {

    private val mAdapter: MallProductAdapter by lazy { MallProductAdapter(arrayListOf()) }
    private lateinit var loadsir: LoadService<Any>

    private var comprehensive: Boolean = true//综合
    private var sales: Boolean = false//销量
    private var price: Boolean = false//价格
    private var searchGoodName = ""
    private var sortType = "1"
    private var mType = "0"

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        activity?.let { StatusBarUtil.setLightMode(it) }
        activity?.let { StatusBarUtil.setColor(it, Color.TRANSPARENT, 0) }
    }

    override fun initView(savedInstanceState: Bundle?) {
        val searchContent = arguments?.getString("searchContent").toString()
        mType = requireArguments().getString("type", "0")
        mDatabind.editQuery.setText(searchContent)

        //监听系统返回键
        activity?.onBackPressedDispatcher?.addCallback(this, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                nav().popBackStack(R.id.fragmentSearchGoods, true)
            }
        })

        mDatabind.editQuery.setOnKeyListener { _, keyCode, event ->
            if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_DOWN) {
                if (!TextUtils.isEmpty(mDatabind.editQuery.text.toString())) {
                    RxToast.showToast("搜索的是:" + mDatabind.editQuery.text.toString())
                    searchResultData()
                } else {
                    RxToast.showToast("请输入需要搜索的内容")
                }
                hideSoftKeyboard(activity)
            }
            false
        }

//        swipeRecyclerView.init(GridLayoutManager(context, 2), mAdapter).addItemDecoration(
//            SpaceItemDecoration(Util.dp2px(context, 3f), Util.dp2px(context, 3f))
//        )

        val layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        mDatabind.layoutList.swipeRecyclerView.addItemDecoration(object : RecyclerView.ItemDecoration() {
            override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
                super.getItemOffsets(outRect, view, parent, state)
                outRect.right = Util.dp2px(context, 5f)//右间距5dp
                outRect.left = Util.dp2px(context, 5f)//左间距5dp
                outRect.top = Util.dp2px(context, 5f)//上间距5dp
                outRect.bottom = Util.dp2px(context, 5f)//下间距5dp
            }
        })
        mDatabind.layoutList.swipeRecyclerView.layoutManager = layoutManager
        mDatabind.layoutList.swipeRecyclerView.adapter = mAdapter

        //状态页配置
        loadsir = loadServiceInit(mDatabind.layoutList.swipeRefreshLayout) {
            //点击重试时触发的操作
            loadsir.showLoading()
            mViewModel.getAppGoodList("", sortType, searchGoodName)
        }

        mDatabind.layoutList.swipeRefreshLayout.init {
            loadsir.showLoading()
            mViewModel.getAppGoodList("", sortType, searchGoodName)
        }

        mAdapter.run {
            setOnItemClickListener { _, _, position ->
                nav().navigateAction(R.id.action_to_fragment_goods_detail, Bundle().apply {
                    putString("id", mAdapter.data[position].id.toString())
                })
            }
        }
    }

    override fun lazyLoadData() {
        super.lazyLoadData()
//        showLoadingAntiShake(getString(R.string.loading))
        searchGoodName = mDatabind.editQuery.text.toString().trim()
        loadsir.showLoading()
        mViewModel.getAppGoodList("", sortType, searchGoodName)
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.goodsListResult.observe(viewLifecycleOwner) {
//            dismissLoadingAntiShake()
            loadListData(it, mAdapter, loadsir, mDatabind.layoutList.swipeRecyclerView, mDatabind.layoutList.swipeRefreshLayout)
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.ivBack, mDatabind.tvSearchResult, mDatabind.findByTotal, mDatabind.findByNum, mDatabind.findByPrice) {
            when (it) {
                mDatabind.ivBack -> {
                    if (mType != "0") {
                        nav().navigateUp()
                    } else {
                        nav().popBackStack(R.id.fragmentSearchGoods, true)
                    }
                }

                mDatabind.tvSearchResult -> {
                    searchResultData()
                }

                mDatabind.findByTotal -> {//综合
                    comprehensiveSearch()
                }

                mDatabind.findByNum -> {//销量
                    salesSearch()
                }

                mDatabind.findByPrice -> {//价格
                    priceSearch()
                }
            }
        }
    }

    /** 价格搜索 */
    var isCheckedPrice = true
    private fun priceSearch() {
        sales = false
        price = true
        comprehensive = false
        if (isCheckedPrice) {
            sortType = "6"
            mDatabind.findByPriceIc.setImageResource(R.mipmap.down_srl)
        } else {
            sortType = "5"
            mDatabind.findByPriceIc.setImageResource(R.mipmap.up_srl)
        }
        isCheckedPrice = !isCheckedPrice

        mDatabind.findByPriceTv.setTextColor(Color.parseColor("#1081DE"))

        mDatabind.findByTotalIc.setImageResource(R.mipmap.grey_srl)
        mDatabind.findByTotalTv.setTextColor(Color.parseColor("#8F8F8F"))

        mDatabind.findByNumIc.setImageResource(R.mipmap.grey_srl)
        mDatabind.findByNumTv.setTextColor(Color.parseColor("#8F8F8F"))
        searchResultData()
    }

    /** 销量搜索 */
    var isCheckedSales = true
    private fun salesSearch() {
        sales = true
        price = false
        comprehensive = false
        if (isCheckedSales) {
            sortType = "4"
            mDatabind.findByNumIc.setImageResource(R.mipmap.down_srl)
        } else {
            sortType = "3"
            mDatabind.findByNumIc.setImageResource(R.mipmap.up_srl)
        }
        isCheckedSales = !isCheckedSales

        mDatabind.findByNumTv.setTextColor(Color.parseColor("#1081DE"))

        mDatabind.findByTotalIc.setImageResource(R.mipmap.grey_srl)
        mDatabind.findByTotalTv.setTextColor(Color.parseColor("#8F8F8F"))

        mDatabind.findByPriceIc.setImageResource(R.mipmap.grey_srl)
        mDatabind.findByPriceTv.setTextColor(Color.parseColor("#8F8F8F"))
        searchResultData()
    }

    /** 综合搜索 */
    private var isCheckedTotal = true
    private fun comprehensiveSearch() {
        sales = false
        price = false
        comprehensive = true
        if (isCheckedTotal) {
            sortType = "1"//上架排序正序
            mDatabind.findByTotalIc.setImageResource(R.mipmap.up_srl)
        } else {
            sortType = "2"//上架排序倒序
            mDatabind.findByTotalIc.setImageResource(R.mipmap.down_srl)
        }
        mDatabind.findByTotalTv.setTextColor(Color.parseColor("#1081DE"))

        mDatabind.findByNumIc.setImageResource(R.mipmap.grey_srl)
        mDatabind.findByNumTv.setTextColor(Color.parseColor("#8F8F8F"))

        mDatabind.findByPriceIc.setImageResource(R.mipmap.grey_srl)
        mDatabind.findByPriceTv.setTextColor(Color.parseColor("#8F8F8F"))
        isCheckedTotal = !isCheckedTotal
        searchResultData()
    }

    private fun searchResultData() {
        lazyLoadData()
    }
}
